import CryptoJS from 'crypto-js'
import APPConfig from './../resource/file/appConfig/JJAPPConfig.js'
import JJUtil from './JJUtil'

let g_deviceNo = ''

export default class JJDeviceUtil {
    
    static getDeviceNo() {
        
        if (!JJUtil.isEmpty(g_deviceNo)) {
            return g_deviceNo;
        }
 
        const keyDecryptValue = APPConfig.channelName + '_JJDeviceHelper_deviceNo_key';
        
        let key = CryptoJS.MD5(keyDecryptValue).toString()
        if (!APPConfig.isStorageCrypt) {
            key = keyDecryptValue
        }
        key  = key ? key : keyDecryptValue

        const storageDeviceNo = localStorage.getItem(key)
        if (JJUtil.isNotNull(storageDeviceNo) && storageDeviceNo.length > 0) {
            g_deviceNo = storageDeviceNo
            return storageDeviceNo
        }

        let deviceNo = ''
        
        for (let i = 0; i < 50; ++i) {
            deviceNo = deviceNo + JJUtil.random(1, 100000).toString() + '_'
        }

        const dateStr = Date.now().toString()
        deviceNo = deviceNo + dateStr + '_'

        const md5DeviceNo = CryptoJS.MD5(deviceNo).toString()
        if (JJUtil.isNotNull(md5DeviceNo) && md5DeviceNo.length > 0) {
            deviceNo = md5DeviceNo
        }

        g_deviceNo = deviceNo
        if (!JJUtil.isEmpty(g_deviceNo)) {
            localStorage.setItem(key, g_deviceNo)
        }
        
        return g_deviceNo
    }

    static getTerminalType() {
        if (JJDeviceUtil.isIOS()) {
            return '03'
        } else if (JJDeviceUtil.isAndroid()) {
            return '02'
        } else {
            return '07'
        }
    }

    static isInWechat() {
        const ua = window.navigator.userAgent
        if (/MicroMessenger/.test(ua)) {
            return true;
        } else {
            return false;
        }
    }

    static isInAlipay() {
        const ua = window.navigator.userAgent
        if (/AlipayClient/.test(ua)) {
            return true;
        } else {
            return false;
        }
    }

    static isIOS() {
        const ua = window.navigator.userAgent
        const isIOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        return isIOS
    }

    static isAndroid() {
        const ua = window.navigator.userAgent
        const isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1
        return isAndroid
    }
}
